package hang.com.mvptest;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Adapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.google.gson.Gson;
import com.tencent.android.tpush.XGPushConfig;
import com.tencent.android.tpush.XGPushManager;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Path;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.main_lv_list)
    ListView mainLvList;
    List<Map<String,String>> data = new LinkedList<>() ;
    //SimpleAdapter adapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);





        SimpleAdapter adapter = new SimpleAdapter(this,data,R.layout.list_item,new String[]{"name","description"},new int[]{R.id.name,R.id.description});
        mainLvList.setAdapter(adapter);

        // network request
        Retrofit retrofit = new Retrofit.Builder()
                .client(new OkHttpClient())
                .baseUrl("https:/api.github.com")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        GitHubService service = retrofit.create(GitHubService.class);
        Call<List<Repo>> call = service.listRepos("jinghang");

        Context ctt = this;
        call.enqueue(new Callback<List<Repo>>() {
            @Override
            public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
                List<Repo> list = response.body();
                Log.d("hang", new Gson().toJson(list));

                for(Repo r:list){
                    Map<String,String> map = new HashMap<>();
                    map.put("name",r.name);
                    map.put("description",r.description);
                    data.add(map);
                }
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onFailure(Call<List<Repo>> call, Throwable t) {
                Log.d("hang", "Error " + t.toString());
            }
        });
    }

    class Repo {
        public String id;
        public String name;
        public String full_name;
        public String description;
        public String html_url;
    }

    public interface GitHubService {
        @GET("users/{user}/repos")
        Call<List<Repo>> listRepos(@Path("user") String user);
    }
}
